package com.wx.md.adb;

import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import org.springframework.stereotype.Component;

@Component
public class AdbUtils {
    IAdbEnv defaultAdb = new DefaultAdbEnv();
    AndroidDebugBridge androidDebugBridge = null;




    private AdbUtils() {
    }

    public AdbUtils init() {
        String adbPath = defaultAdb.getAdbPath();
        AndroidDebugBridge.init(false);
        androidDebugBridge = AndroidDebugBridge.createBridge(adbPath, true);
        if (androidDebugBridge != null) {
            System.out.println("初始化adb成功！");
        } else {
            System.out.println("初始化adb失败！");
        }
        return this;
    }

    private void disconnect() {
        AndroidDebugBridge.disconnectBridge();
    }

    private boolean waitForDeviceList() {
        int maxWaittingTime = 100;
        int interval = 10;
        if (androidDebugBridge != null) {
            while (!androidDebugBridge.hasInitialDeviceList()) {
                try {
                    Thread.sleep(interval);
                } catch (InterruptedException e) {
                    break;
                }
                maxWaittingTime -= 1;
                if (maxWaittingTime == 0) {
                    disconnect();
                    return false;
                }
            }
        } else {
            return false;
        }
        return true;
    }

    // 获取连接的设备列表
    public IDevice[] getAllDevices() {
        IDevice[] deviceList = null;
        if (androidDebugBridge != null) {
            if (waitForDeviceList()) {
                return androidDebugBridge.getDevices();
            }
        }
        return null;
    }

    // 获取连接的设备列表
    public IDevice getIDeviceBySn(String serialNumber) {
        IDevice[] deviceList = null;
        if (androidDebugBridge != null) {
            if (waitForDeviceList()) {
                deviceList = androidDebugBridge.getDevices();
                for (IDevice device : deviceList) {
                    //System.out.println(device.getName());
                    if (device.getSerialNumber().startsWith(serialNumber)) {
                        return device;
                    }
                    System.out.println(device.getSerialNumber());
                    System.out.println(device.getState());
                }
            }
        }
        return null;
    }


}
